<template>
  <el-tree
    :data="menuList"
    show-checkbox
    default-expand-all
    node-key="id"
    ref="tree"
    highlight-current
    :check-on-click-node="true"
    @check-change="checkChange"
    :props="defaultProps">
  </el-tree>
</template>

<script>
import Menu from "@/api/menu";
export default {
  name: "AuthMenu",
  props: {
    uid: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      menuList : [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    };
  },

  methods: {
    getMenuByUser(){
      Menu.getMenuByUser(this.uid).then(data => {
        let ids = [];
        data.forEach(item => {
          ids.push(item.id);
        });
        this.$refs.tree.setCheckedKeys(ids);
      })
    },
    getAllMenu() {
      Menu.getMenuList({ index: 0, limit: 1000 }).then(data => {
        if(data && data.list){
          let list = {};
          data.list.forEach(elem => {
            if (elem.parent == 0 && !list["menu_" + elem.id]) {
              elem.children = [];
              elem.open = false;
              elem.active = false;
              list["menu_" + elem.id] = elem;
            } else {
              elem.active = false;
              list["menu_" + elem.parent].children.push(elem);
            }
          });

          Object.keys(list).forEach(key => this.menuList.push(list[key]));

          this.getMenuByUser();
        }
      });
    },
    checkChange(){
      let checked_nodes = this.$refs.tree.getCheckedNodes(false,true);
      let menu_arr = [];
      checked_nodes.forEach(node => {
        menu_arr.push(node.id);
      });

      this.$store.commit('selectMenu',menu_arr);

      // console.log(this.$refs.tree.getCheckedNodes(false,true));
    }
    
  },

  watch:{
    uid : function (val) {
      this.uid = val;
      this.getMenuByUser();
    }
  },

  mounted() {
    // this.getMenuByUser(true);
  },
  created() {
    this.getAllMenu();
  }
};
</script>
<style rel="stylesheet/less" lang="less" scoped>
</style>
